/*
 * MaxOccursValidator.java
 * 
 * Created on 23-Aug-2007, 16:50:04
 * 
 * Copyright (C)
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

package com.grubby.databean.constraints.validation;

import com.grubby.databean.constraints.annotation.MaxOccurs;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.Map;

/**
 * A validator for the {@link MaxOccurs MaxOccurs} constraint.
 * <p>
 * Note this has been adapted from an Annotation processing example created by 
 * Anders Holmgren of Sun Microsystems
 * </p>
 * @see MaxOccurs
 *
 * @author Anders Holmgren, with alterations by A. HARMEL-LAW. 
 * E: andrew.harmel.law@gmail.com
 * @version 0.1
 */
public class MaxOccursValidator extends AbstractConstraintValidator {
    /**
     * Constructs a MaxOccursValidator object.
     */
    // suppress the unchecked warning for unchecked generic array creation
    @SuppressWarnings("unchecked")
    public MaxOccursValidator() {
        super(MaxOccurs.class);
    }

    public ConstraintViolation validate(Object objValue, Annotation constraint) {
        
        this.ensureConstraintIsSupported(constraint);
        
        /*
         * Figure out the number of items in the collection or map.
         * Null collections are treated the same as empty collections. i.e.
         * they both have 0 items.
         */
        int numItems = 0;
        if (objValue != null) {
            if (!(objValue instanceof Collection) && !(objValue instanceof Map))
                throw new IllegalArgumentException("MaxOccurs constraint can only be applied to subclasses of Collection or Map.");

            Collection col = (objValue instanceof Collection) ? 
                (Collection)objValue : ((Map)objValue).keySet();
            numItems = col.size();
        }
        
        MaxOccurs mo = (MaxOccurs)constraint;
        ConstraintViolation result = null;

        if (numItems > mo.value()) {
            result = new ConstraintViolation(mo,
                "MaxOccurs constraint violated. Number of items " + numItems + 
                " is more than max " + mo.value());
        }

        return result;
    }
}
